#define _CRT_SECURE_NO_WARNINGS
#include"SeqList.h"

void SeqListInit(SeqList* ps)
{
	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SeqListDestroy(SeqList* ps)
{
	assert(ps);
	if (ps->arr)
	{
		free(ps->arr);
		ps->arr = NULL;
		ps->size = 0;
		ps->capacity = 0;
	}
}

void SeqListPrint(SeqList* ps)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->size; ++i)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}

void SeqListCheck(SeqList* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		int newc = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDateType* tmp = realloc(ps->arr, newc * sizeof(SLDateType));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->arr = tmp;
		ps->capacity = newc;
	}
}

void SeqListPushBack(SeqList* ps, SLDateType x)
{
	/*assert(ps);
	SeqListCheck(ps);
	ps->arr[ps->size] = x;
	++ps->size;*/

	SeqListInsert(ps, ps->size, x);
}

void SeqListPushFront(SeqList* ps, SLDateType x)
{
	/*assert(ps);
	SeqListCheck(ps);
	int i = 0;
	for (i = ps->size - 1; i >= 0; --i)
	{
		ps->arr[i + 1] = ps->arr[i];
	}
	ps->arr[0] = x;
	++ps->size;*/

	SeqListInsert(ps, 0, x);
}

void SeqListPopFront(SeqList* ps)
{
	/*assert(ps);
	assert(ps->size > 0);
	int i = 0;
	for (i = 0; i < ps->size - 1; ++i)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	--ps->size;*/

	SeqListErase(ps, 0);
}

void SeqListPopBack(SeqList* ps)
{
	/*assert(ps);
	assert(ps->size > 0);
	--ps->size;*/

	SeqListErase(ps, ps->size - 1);
}

int SeqListFind(SeqList* ps, SLDateType x)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->size; ++i)
	{
		if (ps->arr[i] == x)
			return i;
	}
	return -1;
}

void SeqListInsert(SeqList* ps, size_t pos, SLDateType x)
{
	assert(ps);
	assert(pos <= ps->size);
	SeqListCheck(ps);
	int i = ps->size - 1;
	while (i >= (int)pos)
	{
		ps->arr[i + 1] = ps->arr[i];
		--i;
	}
	ps->arr[pos] = x;
	++ps->size;
}

void SeqListErase(SeqList* ps, size_t pos)
{
	assert(ps);
	assert(pos < ps->size);
	int i = pos;
	while (i < ps->size)
	{
		ps->arr[i] = ps->arr[i + 1];
		++i;
	}
	--ps->size;
}